<template>
  <a-form ref="appFormRef" class="app-form" :model="appModel">
    <a-form-item
      class="mb-0"
      label="授权应用"
      :colon="false"
      :rules="{ required, message: '请选择应用' }"
      name="selectedApps"
    >
      <a-checkbox-group :value="appModel.selectedApps" class="pl-4.5" :disabled="disabled" @change="change">
        <a-checkbox
          v-for="(el, i) in subAppData"
          :key="el.value"
          :value="el.value"
          class="flex flex-row items-center !ml-0"
          :class="[i < subAppData.length - 1 ? 'mb-4.5' : '']"
        >
          <span> {{ el.text }} </span>
          <span v-if="el.des" class="text-color-secondary text-xs ml-2">({{ el.des }})</span>
        </a-checkbox>
      </a-checkbox-group>
    </a-form-item>
  </a-form>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { AiotSubApp, getAiotSubAppData } from "/@/base/data";

const props = defineProps<{
  value: AiotSubApp[];
  required?: boolean;
  disabled?: boolean;
  singleSelect?: boolean;
  exceptApps?: AiotSubApp[];
}>();

const emits = defineEmits(["update:value"]);

const appModel = ref<{
  selectedApps: AiotSubApp[];
}>({
  selectedApps: props.value,
});
watch(
  () => props.disabled,
  () => {
    appFormRef.value.clearValidate();
  }
);
watch(
  appModel,
  (val) => {
    enablePropsValueWatch = false;
    emits("update:value", val.selectedApps);
    nextTick(() => {
      enablePropsValueWatch = true;
    });
  },
  {
    deep: true,
  }
);
let enablePropsValueWatch = true;
watch(
  () => props.value,
  (val) => {
    if (!enablePropsValueWatch) return;
    appModel.value.selectedApps = val;
  }
);
const subAppData = ref(getAiotSubAppData(props.exceptApps));
watch(
  () => props.exceptApps,
  (v) => {
    subAppData.value = getAiotSubAppData(v);
  }
);
function change(vals) {
  if (props.singleSelect) {
    appModel.value.selectedApps = vals[vals.length - 1] ? [vals[vals.length - 1]] : [];
  } else {
    appModel.value.selectedApps = vals;
  }
}
const appFormRef = ref();
defineExpose({
  validate() {
    return appFormRef.value.validate();
  },
});
</script>
<style lang="less">
.app-form {
  .ant-form-item-label > label {
    height: auto;
  }
  .ant-checkbox {
    top: 0;
  }
  .ant-form-item-explain-error {
    padding-left: 16px;
  }
}
</style>
